import React, { useState, useEffect } from 'react';
import { message, Spin } from 'antd';
import Toolbar from './Toolbar';
import Breadcrumb from './Breadcrumb';
import UploadArea from './UploadArea';
import FileList from './FileList';
import { ossApi } from '../utils/ossApi';
import { FileItem, FolderItem } from '../types';

const FileManager: React.FC = () => {
  const [currentFolder, setCurrentFolder] = useState('');
  const [folderPath, setFolderPath] = useState<string[]>([]);
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [folders, setFolders] = useState<FolderItem[]>([]);
  const [files, setFiles] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [operationLoading, setOperationLoading] = useState(false);
  const [operationText, setOperationText] = useState('');
  const [dragOver, setDragOver] = useState(false);

  // 加载文件列表
  const loadFileList = async () => {
    setLoading(true);
    try {
      if (currentFolder === '') {
        // 获取根目录文件夹列表
        const data = await ossApi.getFolders();
        setFolders(data.folders || []);
        setFiles([]);
      } else {
        // 获取指定文件夹内容
        const data = await ossApi.getFolderContents(currentFolder);
        setFolders(data.subFolders || []);
        setFiles(data.files || []);
      }
    } catch (error: any) {
      message.error('加载失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 导航到文件夹
  const navigateToFolder = (folderName: string) => {
    if (folderName === '') {
      setCurrentFolder('');
      setFolderPath([]);
    } else {
      if (currentFolder === '') {
        setCurrentFolder(folderName);
        setFolderPath([folderName]);
      } else {
        setCurrentFolder(currentFolder + '/' + folderName);
        setFolderPath([...folderPath, folderName]);
      }
    }
    setSelectedItems(new Set());
  };

  // 创建文件夹
  const createFolder = async (folderName: string) => {
    setOperationLoading(true);
    setOperationText('正在创建文件夹...');
    try {
      const fullPath = currentFolder ? `${currentFolder}/${folderName}` : folderName;
      await ossApi.createFolder(fullPath);
      message.success('文件夹创建成功!');
      loadFileList();
    } catch (error: any) {
      message.error('创建文件夹失败: ' + (error.message || '未知错误'));
    } finally {
      setOperationLoading(false);
      setOperationText('');
    }
  };

  // 上传单个文件
  const uploadSingleFile = async (file: File) => {
    setOperationLoading(true);
    setOperationText(`正在上传文件: ${file.name}...`);
    try {
      const uploadFolder = currentFolder || 'uploads';
      const result = await ossApi.uploadSingleFile(file, uploadFolder);
      message.success(`文件上传成功!`);
      loadFileList();
    } catch (error: any) {
      message.error('文件上传失败: ' + (error.message || '未知错误'));
    } finally {
      setOperationLoading(false);
      setOperationText('');
    }
  };

  // 批量上传文件
  const uploadMultipleFiles = async (files: File[]) => {
    setOperationLoading(true);
    setOperationText(`正在批量上传 ${files.length} 个文件...`);
    try {
      const uploadFolder = currentFolder || 'uploads';
      const result = await ossApi.uploadMultipleFiles(files, uploadFolder);
      message.success(`批量上传完成! 成功: ${result.success}, 失败: ${result.failed}`);
      loadFileList();
    } catch (error: any) {
      message.error('批量上传失败: ' + (error.message || '未知错误'));
    } finally {
      setOperationLoading(false);
      setOperationText('');
    }
  };

  // 删除选中项目
  const deleteSelected = async () => {
    if (selectedItems.size === 0) return;
    
    setOperationLoading(true);
    setOperationText(`正在删除 ${selectedItems.size} 个项目...`);
    try {
      const deletePromises: Promise<any>[] = [];
      
      selectedItems.forEach(item => {
        const [type, name] = item.split(':');
        
        if (type === 'file') {
          deletePromises.push(ossApi.deleteFile(name));
        } else if (type === 'folder') {
          deletePromises.push(ossApi.deleteFolder(name));
        }
      });
      
      const results = await Promise.all(deletePromises);
      const successful = results.filter(r => r.success).length;
      const failed = results.length - successful;
      
      if (successful > 0) {
        message.success(`删除完成! 成功: ${successful}, 失败: ${failed}`);
        setSelectedItems(new Set());
        loadFileList();
      } else {
        message.error('删除失败');
      }
    } catch (error: any) {
      message.error('删除错误: ' + (error.message || '未知错误'));
    } finally {
      setOperationLoading(false);
      setOperationText('');
    }
  };

  // 选择项目
  const selectItem = (type: 'file' | 'folder', name: string) => {
    const itemKey = `${type}:${name}`;
    const newSelected = new Set(selectedItems);
    
    if (newSelected.has(itemKey)) {
      newSelected.delete(itemKey);
    } else {
      newSelected.add(itemKey);
    }
    
    setSelectedItems(newSelected);
  };

  // 处理文件拖拽
  const handleDrop = (files: File[]) => {
    if (files.length === 1) {
      uploadSingleFile(files[0]);
    } else if (files.length > 1) {
      uploadMultipleFiles(files);
    }
  };

  useEffect(() => {
    loadFileList();
  }, [currentFolder]);

  return (
    <div className="w-full max-w-7xl mx-auto bg-white rounded-2xl shadow-lg overflow-hidden my-8">
      {/* Header */}
      <div className="bg-gradient-to-r from-indigo-500 to-purple-600 text-white p-6 text-center">
        <h1 className="text-3xl font-bold mb-2">🗂️ AI人设资源管理系统</h1>
        {/* <p className="opacity-90">支持上传：图片、视频、音频、文档等</p> */}
      </div>

      {/* 操作Loading遮罩 */}
      {operationLoading && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-8 flex flex-col items-center space-y-4 max-w-sm mx-4">
            <Spin size="large" />
            <div className="text-lg font-medium text-gray-800">{operationText}</div>
            <div className="text-sm text-gray-500">请稍候...</div>
          </div>
        </div>
      )}

      <div className="p-6">
        {/* 工具栏 */}
        <Toolbar
          onRefresh={loadFileList}
          onCreateFolder={createFolder}
          onUploadSingle={uploadSingleFile}
          onUploadMultiple={uploadMultipleFiles}
          onDeleteSelected={deleteSelected}
          onGoToRoot={() => navigateToFolder('')}
          hasSelectedItems={selectedItems.size > 0}
          disabled={operationLoading}
        />

        {/* 面包屑导航 */}
        <Breadcrumb
          folderPath={folderPath}
          onNavigate={navigateToFolder}
        />

        {/* 当前文件夹显示 */}
        <div className="font-bold text-blue-600 mb-4">
          当前位置: /{currentFolder}
        </div>

        {/* 拖拽上传区域 */}
        <UploadArea onDrop={handleDrop} disabled={operationLoading} />

        {/* 文件列表 */}
        <FileList
          folders={folders}
          files={files}
          loading={loading}
          selectedItems={selectedItems}
          onSelectItem={selectItem}
          onNavigateToFolder={navigateToFolder}
          disabled={operationLoading}
        />

        {/* 状态信息区域 */}
        <div id="status" className="mt-4" style={{ display: 'none' }}></div>
      </div>
    </div>
  );
};

export default FileManager; 